<template>
  <div>
    <!-- <a-button type="primary" @click="addNewThird()" class="btn_primary_color add_btn" v-show="btnShow"> 新增第三人 </a-button> -->
    <div v-if="thirdPersonMap != null && Object.keys(thirdPersonMap).length != 0">
      <!-- 人员信息 -->
      <a-collapse v-model="activeKey" v-for="(item, key, index) in thirdPersonMap" :key="index" :bordered="false">
        <a-collapse-panel :key="key" :header="typeLable(key)" v-if="key == Tp_applicantValue.CITIZEN">
          <a-table
            :scroll="{ x: 800, y: 400 }"
            :columns="columns"
            :data-source="thirdPersonMap[key]"
            rowKey="id"
            :pagination="false"
            :loading="loading"
            bordered
          >

            <span slot="index" slot-scope="text, record, index">
              {{ index + 1 }}
            </span>

            <span slot="nameSlot" slot-scope="text, record">
              <div class="beyond_hiding">
                <a-tooltip placement="topLeft">
                  <template slot="title">
                    <span>{{ record.name }}</span>
                  </template>
                  {{ record.name }}
                </a-tooltip>
              </div>
            </span>
            <span slot="cardnoSlot" slot-scope="text, record">
              <div class="beyond_hiding">
                <a-tooltip placement="topLeft">
                  <template slot="title">
                    <span>{{ record.cardno }}</span>
                  </template>
                  {{ record.cardno }}
                </a-tooltip>
              </div>
            </span>
            <span slot="addrSlot" slot-scope="text, record">
              <div class="beyond_hiding">
                <a-tooltip placement="topLeft">
                  <template slot="title">
                    <span>{{ record.addr }}</span>
                  </template>
                  {{ record.addr }}
                </a-tooltip>
              </div>
            </span>

            <span slot="typeSlot" slot-scope="text, record">
              <a-tooltip placement="top">
                <template slot="title">
                  <span>{{ typeLable(record.type) }}</span>
                </template>
                {{ typeLable(record.type) }}
              </a-tooltip>
            </span>

            <span slot="cardtypeSlot" slot-scope="text, record">
              <a-tooltip placement="top">
                <template slot="title">
                  <span>{{ cardTypeLable(record.cardtype) }}</span>
                </template>
                {{ cardTypeLable(record.cardtype) }}
              </a-tooltip>
            </span>

            <span slot="filecardSlot" slot-scope="text, record">
              <div v-if="record.filecardList && record.filecardList.length > 0">
                <a v-for="item in record.filecardList" :key="item.id" class="file-css hover-div">
                  <span @click="previewFile(item)">
                    <a-icon type="folder" theme="filled" />
                    {{ item.filename }}
                  </span>
                  <a-icon type="download" v-if="btnShow" @click="downloadFile(item)" />
                  <a-popconfirm title="是否删除?" @confirm="() => deleteFile(record, item, 0)">
                    <a-icon type="delete" v-if="btnShow" class="hover-delete" />
                  </a-popconfirm>
                </a>
              </div>
              <div v-else>未上传附件</div>
            </span>

            <span slot="thirdEvidenceSlot" slot-scope="text, record">
              <div v-if="record.thirdEvidenceList && record.thirdEvidenceList.length > 0">
                <a v-for="item in record.thirdEvidenceList" :key="item.id" class="file-css hover-div">
                  <span @click="previewFile(item)">
                    <a-icon type="folder" theme="filled" />
                    {{ item.filename }}
                  </span>
                  <a-icon type="download" v-if="btnShow" @click="downloadFile(item)" />
                  <a-popconfirm title="是否删除?" @confirm="() => deleteFile(record, item, 2)">
                    <a-icon type="delete" v-if="btnShow" class="hover-delete" />
                  </a-popconfirm>
                </a>
              </div>
              <div v-else>未上传附件</div>
            </span>

            <span slot="operation" slot-scope="text, record">
              <template>
                <div>
                  <a @click="uploadFile(record, 0)" v-show="btnShow" class="link_css">上传身份证明</a>
                  <a @click="uploadFile(record, 2)" v-show="btnShow" class="link_css">上传第三人材料</a>
                </div>
                <span v-if="btnShow">
                  <a @click="editThirdPerson(record)" class="link_css">编辑</a>
                </span>
                <span v-if="record.filecardList && record.filecardList.length > 0">
                  <a @click="downloadFiles(record, 1)" class="link_css">全部下载</a>
                </span>
              </template>
            </span>
          </a-table>
        </a-collapse-panel>
        <a-collapse-panel :key="key" :header="typeLable(key)" v-if="key == Tp_applicantValue.UNIT">
          <a-table
            :scroll="{ x: 800, y: 400 }"
            :columns="unitColumns"
            :data-source="thirdPersonMap[key]"
            rowKey="id"
            :pagination="false"
            :loading="loading"
            bordered
          >

            <span slot="index" slot-scope="text, record, index">
              {{ index + 1 }}
            </span>
            <span slot="typeSlot" slot-scope="text, record">
              <a-tooltip placement="top">
                <template slot="title">
                  <span>{{ typeLable(record.type) }}</span>
                </template>
                {{ typeLable(record.type) }}
              </a-tooltip>
            </span>

            <span slot="doccardSlot" slot-scope="text, record">
              <div v-if="record.doccardList && record.doccardList.length > 0">
                <a v-for="item in record.doccardList" :key="item.id" class="file-css hover-div">
                  <span @click="previewFile(item)" >
                    <a-icon type="folder" theme="filled" />
                    {{ item.filename }}
                  </span>
                  <a-icon type="download" v-if="btnShow" @click="downloadFile(item)" />
                  <a-popconfirm title="是否删除?" @confirm="() => deleteFile(record, item, 1)" >
                    <a-icon v-if="btnShow" type="delete" class="hover-delete" />
                  </a-popconfirm>
                </a>
              </div>
              <div v-else>未上传附件</div>
            </span>

            <span slot="thirdEvidenceSlot" slot-scope="text, record">
              <div v-if="record.thirdEvidenceList && record.thirdEvidenceList.length > 0">
                <a v-for="item in record.thirdEvidenceList" :key="item.id" class="file-css hover-div">
                  <span @click="previewFile(item)">
                    <a-icon type="folder" theme="filled" />
                    {{ item.filename }}
                  </span>
                  <a-icon type="download" v-if="btnShow" @click="downloadFile(item)" />
                  <a-popconfirm title="是否删除?" @confirm="() => deleteFile(record, item, 2)">
                    <a-icon type="delete" v-if="btnShow" class="hover-delete" />
                  </a-popconfirm>
                </a>
              </div>
              <div v-else>未上传附件</div>
            </span>

            <span slot="operation" slot-scope="text, record">
              <template>
                <div>
                  <a @click="uploadFile(record, 1)" v-show="btnShow" class="link_css">上传身份证明书</a>
                  <a @click="uploadFile(record, 2)" v-show="btnShow" class="link_css">上传第三人材料</a>
                </div>
                <span v-if="btnShow">
                  <a @click="editThirdPerson(record)" class="link_css">编辑</a>
                </span>
                <span v-if="record.doccardList && record.doccardList.length > 0">
                  <a @click="downloadFiles(record, 2)" class="link_css">全部下载</a>
                </span>
              </template>
            </span>
          </a-table>
        </a-collapse-panel>
      </a-collapse>
      <!-- 申请材料 -->
      <!-- <ThirdPersonInventory :applyid="applyid" /> -->
    </div>
    <a-empty v-else style="min-height: 300px" />

    <MultiUploadBasic ref="multiUploadBasic" @importFileFun="importFileFun"></MultiUploadBasic>
    <ThirdPersonAddView ref="thirdPersonAddRef" :applyid="applyid" @reload="getThirdPerson"></ThirdPersonAddView>
  </div>
</template>
<script>
import { saveMaterialRepeat } from '@/api/accept/aprv_process_materials'
import { getThirdWithGroup, updateAttachId, deleteAttachId } from '@/api/accept/apl_thirdper'
import { Tp_applicantList, Tp_applicantValue } from '@/enumeration/Tp_applicant'
import { Tp_cardList } from '@/enumeration/Tp_card'
import { minioUploadMore } from '@/api/base/file'
import { kkfilePreview } from '@/utils/util.js'
import { FILETYPE, FILESIZE } from '@/store/mutation-types'
import { Tp_procmaterialValue } from '@/enumeration/Tp_procmaterial'
import { Tp_proctypeValue } from  '@/enumeration/Tp_proctype'
import { APP_USER } from '@/store/mutation-types.js'
import storage from 'store'
export default {
  props: {
    applyid: {
      // 申请id
      type: String,
      required: true
    },
    isEditModel: {
      type: Boolean,
      default: false,
      required: true
    }
  },
  data () {
    return {
      loading: false, // 遮罩是否显示
      Tp_applicant: Tp_applicantList,
      Tp_applicantValue: Tp_applicantValue,
      Tp_card: Tp_cardList,
      currentUser: storage.get(APP_USER), // 登录人信息
      Tp_procmaterialValue: Tp_procmaterialValue,
      Tp_proctypeValue: Tp_proctypeValue,
      columns: [
        // 表头配置
        {
          title: '序号',
          align: 'center',
          width: '80px',
          scopedSlots: { customRender: 'index' }
        },
        {
          title: '第三人类型',
          width: '150px',
          key: 'type',
          dataIndex: 'type',
          scopedSlots: { customRender: 'typeSlot' }
        },
        {
          title: '名称',
          width: '150px',
          key: 'name',
          dataIndex: 'name',
          scopedSlots: { customRender: 'nameSlot' }
        },
        {
          title: '证件类型',
          key: 'cardtype',
          dataIndex: 'cardtype',
          width: '120px',
          scopedSlots: { customRender: 'cardtypeSlot' }
        },
        {
          title: '证件号',
          key: 'cardno',
          dataIndex: 'cardno',
          width: '150px',
          scopedSlots: { customRender: 'cardnoSlot' }
        },
        {
          title: '联系号码',
          key: 'tel',
          dataIndex: 'tel',
          width: '150px'
        },
        {
          title: '联系地址',
          key: 'addr',
          dataIndex: 'addr',
          width: '250px',
          scopedSlots: { customRender: 'addrSlot' }
        },
        {
          title: '身份证明',
          dataIndex: 'filecardList',
          key: 'filecardList',
          width: '250px',
          scopedSlots: { customRender: 'filecardSlot' }
        },
        {
          title: '第三人材料证明',
          dataIndex: 'thirdEvidenceList',
          key: 'thirdEvidenceList',
          width: '250px',
          scopedSlots: { customRender: 'thirdEvidenceSlot' }
        },
        {
          title: '操作',
          dataIndex: 'operation',
          width: '150px',
          fixed: 'right',
          scopedSlots: { customRender: 'operation' }
        }
      ],
      unitColumns: [
        // 表头配置
        {
          title: '序号',
          align: 'center',
          width: '80px',
          scopedSlots: { customRender: 'index' }
        },
        {
          title: '第三人类型',
          width: '150px',
          key: 'type',
          dataIndex: 'type',
          scopedSlots: { customRender: 'typeSlot' }
        },
        {
          title: '名称',
          width: '150px',
          key: 'name',
          dataIndex: 'name'
        },
        {
          title: '证件号',
          key: 'cardno',
          dataIndex: 'cardno',
          width: '150px'
        },
        {
          title: '联系号码',
          key: 'tel',
          dataIndex: 'tel',
          width: '120px'
        },
        {
          title: '法定代表人',
          key: 'manager',
          dataIndex: 'manager',
          width: '150px'
        },
        {
          title: '职务',
          key: 'job',
          dataIndex: 'job',
          width: '150px'
        },
        {
          title: '身份证明书',
          dataIndex: 'doccardList',
          key: 'doccardList',
          width: '250px',
          scopedSlots: { customRender: 'doccardSlot' }
        },
        {
          title: '第三人材料证明',
          dataIndex: 'thirdEvidenceList',
          key: 'thirdEvidenceList',
          width: '250px',
          scopedSlots: { customRender: 'thirdEvidenceSlot' }
        },
        {
          title: '操作',
          dataIndex: 'operation',
          width: '150px',
          fixed: 'right',
          scopedSlots: { customRender: 'operation' }
        }
      ],
      thirdPersonMap: {}, // 第三人数据
      selectData: {}, // 点击按钮选择的行数据
      operateType: undefined, // 操作类型 0：身份证明 1:身份证明书，2：第三人证明材料
      btnShow: true, //  按钮展示
      activeKey: [],
      acceptFileType: FILETYPE
    }
  },
  components: {
    ThirdPersonAddView: () => import('@/views/accept/material/ThirdPersonAddView.vue'),
    ThirdPersonInventory: () => import('@/views/accept/material/ThirdPersonInventory.vue'),
    MultiUploadBasic: () => import('@/views/materials/multiUpload/MultiUploadBasic.vue')
  },
  created () {
    this.getThirdPerson()
    if (this.isEditModel) {
      this.btnShow = true
    } else {
      this.btnShow = false
    }
    // FIXME: 临时放开
    this.btnShow = true
  },
  methods: {
    getThirdPerson () {
      getThirdWithGroup({ applyid: this.applyid }).then((res) => {
        if (res.code == 0) {
          this.thirdPersonMap = res.data
          if (this.thirdPersonMap != null && this.thirdPersonMap != undefined && Object.keys(this.thirdPersonMap).length >= 0) {
            for (const key in this.thirdPersonMap) {
              this.activeKey.push(key)
            }
          }
        } else {
          this.thirdPersonMap = {}
        }
      })
    },
    downloadFile (file) {
      const x = new XMLHttpRequest()
      x.open('GET', file.path, true)
      x.responseType = 'blob'
      x.onload = function (e) {
        const url = window.URL.createObjectURL(x.response)
        const a = document.createElement('a')
        a.href = url
        a.download = file.filename
        a.click()
      }
      x.send()
    },
    downloadFiles (record, type) {
      let fileList = []
      if (type == 1) {
        if (record.filecardList && record.filecardList.length > 0) {
          fileList = record.filecardList
        }
      } else if (type == 2) {
        if (record.doccardList && record.doccardList.length > 0) {
          fileList = record.doccardList
        }
      }
      if (record.thirdEvidenceList && record.thirdEvidenceList.length > 0) {
        fileList = fileList.concat(record.thirdEvidenceList)
      }
      for (const index in fileList) {
        const file = fileList[index]
        const x = new XMLHttpRequest()
        x.open('GET', file.path, true)
        x.responseType = 'blob'
        x.onload = function (e) {
          const url = window.URL.createObjectURL(x.response)
          const a = document.createElement('a')
          a.href = url
          a.download = file.filename
          a.click()
        }
        x.send()
      }
    },
    // 状态转换显示
    typeLable (val) {
      for (const key in this.Tp_applicant) {
        if (this.Tp_applicant[key].value == val) {
          return this.Tp_applicant[key].name
        }
      }
      return val
    },
    cardTypeLable (val) {
      for (const key in this.Tp_card) {
        if (this.Tp_card[key].value == val) {
          return this.Tp_card[key].name
        }
      }
      return val
    },
    // 上传附件
    uploadFile (record, operateType) {
      this.selectData = record
      this.operateType = operateType
      this.$refs.multiUploadBasic.importVisible = true
    },
    /**
     * 确定保存导入数据
     */
     importFileFun (importFileList) {
      console.log('importFileList', importFileList)
      const files = []
      importFileList.forEach((item) => {
        files.push(item)
      })
      this.$refs.multiUploadBasic.loading = true
      if (this.operateType == null || this.operateType == undefined) {
        this.$message.error('操作类型为空')
      }
      if (this.operateType == 0 || this.operateType == 1) {
        minioUploadMore(files).then((res) => {
          if (res.code == 0) {
            let attachs = res.data
            let attachids = []
            attachs.forEach((item) => {
              attachids.push(item.id)
            })
            if (this.selectData.attachid != '' && this.selectData.attachid != null) {
              const selectAttachIds = this.selectData.attachid.split(',')
              attachids = attachids.concat(selectAttachIds)
            }
            if (this.operateType == 0) {
              // 身份证明
              if (this.selectData.filecard != '' && this.selectData.filecard != null) {
                const filecardIds = this.selectData.filecard.split(',')
                attachids = attachids.concat(filecardIds)
              }
            } else if (this.operateType == 1) {
              // 身份证明书
              if (this.selectData.doccard != '' && this.selectData.doccard != null) {
                const doccardIds = this.selectData.doccard.split(',')
                attachids = attachids.concat(doccardIds)
              }
            } else if (this.operateType == 2) {
              // 第三人证据材料
              if (this.selectData.thirdevidence != '' && this.selectData.thirdevidence != null) {
                const thirdEvidenceIds = this.selectData.thirdevidence.split(',')
                attachids = attachids.concat(thirdEvidenceIds)
              }
            }
            updateAttachId({ id: this.selectData.id, type: this.operateType, attachid: attachids.join(',') }).then((res2) => {
              if (res2.code == 0) {
                this.getThirdPerson()
                this.$message.success('上传成功')
                this.$refs.multiUploadBasic.handleCancel()
              } else {
                this.$message.error('上传失败')
                this.$refs.multiUploadBasic.handleCancel()
              }
            })
          }
        }).finally(() => {
          this.$refs.multiUploadBasic.loading = false
        })
      } else if (this.operateType == 2) {
        const param = {
          applyid: this.applyid,
          fileType: this.Tp_procmaterialValue.MATER_INVENTORY,
          busiType: this.Tp_proctypeValue.ACCEPT_ACCEPT,
          userId: this.currentUser.userId,
          userName: this.currentUser.fullname
        }
        saveMaterialRepeat(param, importFileList)
          .then(res => {
            if (res.code !== 0) {
              this.$message.error(res.msg)
            } else {
                let attachs = res.data
                let attachids = []
                attachs.forEach((item) => {
                  attachids.push(item.attachid)
                })
                  // 第三人证据材料
                if (this.selectData.thirdevidence != '' && this.selectData.thirdevidence != null) {
                  const thirdEvidenceIds = this.selectData.thirdevidence.split(',')
                  attachids = attachids.concat(thirdEvidenceIds)
                }
                updateAttachId({ id: this.selectData.id, type: this.operateType, attachid: attachids.join(',') }).then((res2) => {
                  if (res2.code == 0) {
                    this.getThirdPerson()
                    this.$message.success('上传成功')
                    this.$refs.multiUploadBasic.handleCancel()
                  } else {
                    this.$message.error('上传失败')
                    this.$refs.multiUploadBasic.handleCancel()
                  }
                })
            }
          })
          .catch(err => {
            console.log(err, '上传数据失败')
          })
          .finally(() => {
            this.loading = false
          })
      }
    },
    // 删除文件，涉及到接口的调用
    deleteFile (record, file, type) {
      if (type == null || type == undefined) {
        this.$message.error('操作类型为空')
      }
      deleteAttachId({ id: record.id, type: type, attachid: file.id }).then((res) => {
        console.log('deleteAttachId', res.data)
        if (res.code == 0) {
          this.getThirdPerson()
        } else {
          this.$message.success('删除失败')
        }
      })
    },
    // 新增第三人
    addNewThird () {
      this.$refs.thirdPersonAddRef.init(false)
    },
    editThirdPerson (record) {
      this.$refs.thirdPersonAddRef.init(true, record)
    },
    // 预览文件
    previewFile (record) {
      window.open(kkfilePreview(record.path))
    }
  }
}
</script>
<style lang="less" scoped>
.editable-row-operations a {
  margin-right: 8px;
}

.add_btn {
  z-index: 20;
  margin-left: 90%;
}

.file-css {
  display: block;
  margin-bottom: 5px;
  word-break: break-all;
}

.hover-delete {
  display: none;
  color: red;
}

.hover-div:hover .hover-delete {
  display: inline-block;
  padding-left: 10px;
  color: red;
}

// /deep/ .ant-table-tbody > tr > td {
//   border: 0;
// }

// /deep/.ant-table-thead > tr > th {
//   font-size: 16px !important;
//   color: #666666 !important;
//   border: 0;
// }
.link_css {
  display: block;
}
</style>
